package services

import (
	"errors"
	"hft/Database/admin"
	"hft/global"
)

type AboutArticle struct{}

func (*AboutArticle) Create(data *admin.AboutArticle) (err error) {

	res := global.OC_DB.Where("title = ?", data.Title).FirstOrCreate(&data)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("存在相同的文章")
	}

	return nil
}

func (*AboutArticle) Edit(data *admin.AboutArticle) (err error) {

	err = global.OC_DB.Model(&admin.AboutArticle{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"title": data.Title,
		"sort":  data.Sort,
		"cont":  data.Cont,
	}).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*AboutArticle) List(category_id int) (list []*admin.AboutArticle, err error) {

	var newList []*admin.AboutArticle

	global.OC_DB.Where("category_id = ?", category_id).Find(&newList)

	return newList, nil

}

func (*AboutArticle) GetInfo(id int) (data *admin.AboutArticle, err error) {

	var info *admin.AboutArticle

	global.OC_DB.First(&info, id)

	return info, nil
}

func (*AboutArticle) Delete(ids []int) (err error) {

	var list []*admin.AboutArticle

	global.OC_DB.Find(&list, ids)

	global.OC_DB.Unscoped().Delete(&list)

	return nil

}

var AboutArticleService = new(AboutArticle)
